package com.tms.app.tms.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.R;
import com.tms.app.tms.ui.login.LoginAt;
import com.tms.app.tms.utils.DeviceUtil;
import com.tms.app.tms.utils.NetUtils;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.youtu.SystemUtil;
import com.tms.app.tms.widget.CommonDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.edu.zafu.camera.ContNum4CaMan;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class WelcomeActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks,View.OnClickListener {
    public static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
    public Gson gson=new Gson();
    @BindView(R.id.banner_guide_content)
    BGABanner bannerGuideContent;
    @BindView(R.id.button)
    Button button;
    private boolean clicked=false;
    private String[] perms = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CALL_PHONE,
          //  Manifest.permission_group.LOCATION,
            //Manifest.permission_group.STORAGE,
           // Manifest.permission_group.PHONE
    };
    private int targetType=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_welcome);
        ButterKnife.bind(this);
        if (!NetUtils.isNetworkAvailable()){
            CommonDialog.getInstance(this,null,2,"网络异常，请检查网络").show();
            return;
        }
        initView();
        targetType= getIntent().getIntExtra("targetType",1);
    }

   private void  initView(){
        bannerGuideContent.setData(R.mipmap.guide, R.mipmap.guide);
        bannerGuideContent.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                   if (position==1){
                       button.setVisibility(View.VISIBLE);
                   }else {
                       button.setVisibility(View.INVISIBLE);
                   }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
       button.setOnClickListener(this);
    }




    @Override
    protected void onStart() {
        super.onStart();
        requestCodeQRCodePermissions();
    }
    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "扫描二维码需要打开相机和散光灯的权限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
            return;
        }
       // sendDeviceInfo();
        ContNum4CaMan.doSave();
        clicked=true;
    }

    //成功
    @Override
    public void onPermissionsGranted(int requestCode, List<String> permslist) {
        if (permslist.size()>=perms.length){
          //  sendDeviceInfo();
        }
    }
    //失败
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        System.out.println("requestCode = [" + requestCode + "], perms = [" + perms + "]");
//        if (perms!=null&&perms.size()>0){
//            CommonDialog.getInstance(this,null,2,"缺少必要权限,请开启权限后重新打开").show();
//        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void sendDeviceInfo() {
        RequestParams params = new RequestParams(Constant.DEVICE_INFO);
        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        params.setMultipart(true);
        params.addBodyParameter("api_version", Constant.API_VERSION);
        params.addBodyParameter("deviceUUID",getDeviceId() );
        params.addBodyParameter("os","andriod");
        params.addBodyParameter("osVersion", SystemUtil.getSystemVersion());
        params.addBodyParameter("carrierOperator",SystemUtil.getSubscribe(this));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
                BaseResponse json = gson.fromJson(result, BaseResponse.class);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
                clicked=true;
            }
        });
    }

    private  String getDeviceId(){
        String deviceId= SharePreferenceUtil.getString(this,"deviceId","");
        if (deviceId.equals("")){
            deviceId= DeviceUtil.getDeviceId(this);
            SharePreferenceUtil.setValue(this,"deviceId",deviceId);
        }
        return deviceId;
    }


    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.button&&clicked){
            if (targetType==1){
                Intent intent= new Intent(this, cn.edu.zafu.camera.CameraBaiDuActivity.class);
                startActivity(intent);
                finish();
            }else {
                startActivity(new Intent(this,LoginAt.class));
                finish();
            }

        }
    }
}
